const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const bCrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'

router.post('/login', async (req, res) => {
//    验证数据是否符合要求
    if(req.body.username.length>15||req.body.username.length<3
        ||req.body.password.length>20||req.body.password.length<6) {
        res.json({
            'code': 400,
            'result': 'false',
            'type': 'format_error',
            'content': '语法错误，输入表单格式不正确'
        })
        return
    }
    else {
        const data = {
            username: req.body.username,
            password: req.body.password,
        }
        //    判断是否存在该用户
        let sql = 'select * from user where username = ?'
        db.base(sql, data.username, response => {
            //    如果注册用户名已经存在，则判断密码
            if (response.length > 0) {
                //密码正确
                if (bCrypt.compareSync(data.password,response[0].password)){
                    // 生成token
                    const token = jwt.sign({username: data.username},SECRET)
                    res.json({
                        'code': 200,
                        'result': 'true',
                        'type': 'login_success',
                        'content': '成功登录',
                        'username': data.username,
                        'token': token
                    })
                }
                //    密码不正确
                else {
                    res.json({
                        'code': 403,
                        'result': 'false',
                        'type': 'password_error',
                        'content': '密码不正确'
                    })
                }

            }
            //否则返回不存在用户
            else {
                res.json({
                    'code': 403,
                    'result': 'false',
                    'type': 'user_non_exist',
                    'content': '用户未注册'
                })
                return

            }
        })
    }

})
module.exports = router
